import Tkinter
import getopt
import sys

import bare_caliper
import mussel
import trapbox
import canning
import goggles
import msg


startup_config = {'caliper': {'port': '/dev/ttyUSB0'},
                  'chowder': {'prev_measurements': None,
                              'leaf_start_n': 1,
                              'Ai': 0,
                              'cont_flag': False}}


def usage():
    import shore
    print msg.USAGE % shore.VERSION
    sys.exit(0)


def version():
    import shore
    print msg.VERSION % shore.VERSION
    sys.exit(0)


def parse_opts():
    cli_opts = 'hvcf:p:l:'
    cli_long_opts = ['help', 'version', 'continue', 'file=', 'port=', 'leaf=']
    try:
        opts, args = getopt.getopt(sys.argv[1:], cli_opts, cli_long_opts)
    except getopt.GetoptError:
        opts = [(None, None)]
    for opt, arg in opts:
        if opt in ('-h', '--help'):
            usage()
        elif opt in ('-v', '--version'):
            version()
        elif opt in ('-c', '--continue'):
            print ""
            print "Sorry, this feature is not implemented yet."
            print "Send me an e-mail if you'd like to have it."
            usage()
        elif opt in ('-f', '--file'):
            #if not '.csv' in arg:
            #    arg = '%s.csv' % arg
            #trapbox.logfile, trapbox.pickle_ = trapbox.log_and_pickle(arg)
            trapbox.pickle_ = arg
        elif opt in ('-p', '--port'):
            startup_config['caliper']['port'] = arg
        elif opt in ('-l', '--leaf'):
            try:
                startup_config['chowder']['leaf_start_n'] = abs(int(arg)) + 2
            except ValueError:
                print "Not a valid leaf number"
                sys.exit(2)


def load_previous_measurements():
    pm = canning.pickle_jar(trapbox.pickle_, 'open')
    if pm:
        la = canning.LeafArea(pm)
        startup_config['chowder']['Ai'] = sum(la.retrieve()['a'])
        if startup_config['chowder']['leaf_start_n'] == 1:
            last_leaf = max(pm[len(pm)]['leaf_n'])
            startup_config['chowder']['leaf_start_n'] = last_leaf + 2
    return pm


parse_opts()

startup_config['chowder']['prev_measurements'] = load_previous_measurements()

caliper_device = bare_caliper.Caliper(**startup_config['caliper'])
chowder = mussel.Chowder(caliper_device, **startup_config['chowder'])

porthole = Tkinter.Tk()
gui = goggles.GUI(porthole, chowder)
chowder.gui = True
chowder.update_gui('initial')

porthole.mainloop()

# After exiting the main loop, combine new and old measurements, pickle
# them, and stop caliper.
#mussel.combine_time_course_measurements(chowder.complete_measurements)
if len(chowder.complete_measurements) > 1:
    for i in chowder.measurements:
        chowder.measurements[i].reverse()
canning.pickle_jar(trapbox.pickle_, 'pickle', chowder.complete_measurements)
chowder.stop_caliper()

